<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <title>自定义指令2</title>
</head>

<body>
    <div id="main">
        <input type="text" v-change_color v-model="name">
        <div v-add_img="image">
            <div>我是子元素</div>
        </div>
    </div>

</body>
<script>
    //directice
    Vue.directive('focus', {
        // 当被绑定的元素插入到 DOM 中时
        inserted(el) {
            // 获取焦点
            el.focus();
        }
    });
    let vue = new Vue({
        el: "#main",
        data: {
            demo: 'demoname',
            color: "blue",
            name: 'demo',
            image: 'https://img.alicdn.com/imgextra/i1/16381334/O1CN01hY19rb1Lj140e7by5_!!0-saturn_solar.jpg_468x468q75.jpg_.webp'
        },
        directives: {
            focus: {//指令名不能写驼峰
                // 指令的定义
                inserted(el, binding) {
                    el.focus();
                }
            },
            change_color: {//指令名不能写驼峰
                bind(el, binding) {
                    console.log(el.parentNode)
                },
                // 指令的定义
                inserted(el, binding) {
                    console.log(el.parentNode)
                    console.log(binding);
                    el.style.color = binding.value;
                    el.style.margin = "0 auto";
                    el.id = 'demo';
                    el.className = 'calss1';//自己测测
                    el.title = '我是标题';
                },
                update(el, binding) {//vnode更新时触发
                    console.log('update diaoyongle')
                },
                componentUpdated() {//vnode更新完以后触发

                },
                unbind() {//解绑时触发
                }
            },
            add_img: {
                // 指令的定义
                inserted(el, binding) {
                    let imgurl = binding.value;
                    let image = new Image();//js 里面的 图片对象
                    image.src = imgurl;
                    image.onload = function () {//图片加载完时触发
                        //console.log(image);
                        console.log(image.width);
                        console.log(image.height)
                        el.style.width = image.width + "px";
                        el.style.height = image.height + "px";
                        el.style.background = "url(" + imgurl + ")";

                    }

                }
            }

        }
    })
</script>

</html>